package com.yanqu.road.server.gameplayer.module.activity.tongbing;

import com.yanqu.road.dao.impl.player.UserCommonActivityDataDaoImpl;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.autodata.chuhan.config.*;
import com.yanqu.road.entity.autodata.chuhan.data.ChuHanUserData;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eTongBingPosition;
import com.yanqu.road.entity.task.args.activity.TongBingRedPacketValueArgs;
import com.yanqu.road.logic.activity.chuhan.ChuHanConfig;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.pb.activity.ChuHanProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.EarnSpeedModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.tongbing.ChuHanMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.pb.PlayerPb;
import com.yanqu.road.server.pb.ChuHanPb;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

import java.math.BigInteger;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ChuHanModule extends GeneralModule {
    private ChuHanUserData userData;

    public ChuHanModule(GamePlayer player) {
        super(player);
    }

    @Override
    public void afterLogin() {
        chuHanLogin();
    }

    @Override
    public boolean loadData() {
        ChuHanConfig config = ChuHanMgr.getConfig();
        if (config != null && ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            userData = new UserCommonActivityDataDaoImpl<ChuHanUserData>().getUserActivityData(ChuHanUserData.class, config.getActivityInfo().getActivityId(), getUserId());
            if (userData == null) {
                initUserData();
            }
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        if (userData != null) {
            if (userData.isInsertOption()) {
                new UserCommonActivityDataDaoImpl<ChuHanUserData>().add(userData);
            } else if (userData.isUpdateOption()) {
                new UserCommonActivityDataDaoImpl<ChuHanUserData>().update(userData);
            }
        }
        return true;
    }

    /**
     * 刷新活动 || 登录
     */
    public void chuHanLogin() {
        initUserData();
        crossLogin();
        syncConfig();
        syncUserData();
    }

    /**
     * 同步配置
     */
    public void syncConfig() {
        ChuHanConfig config = ChuHanMgr.getConfig();
        if (config != null && ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            ChuHanProto.ChuHanSyncConfigRespMsg.Builder builder = ChuHanPb.parseChuHanSyncConfigRespMsg(config, player.getUserInfo().getLanguage());
            player.sendPacket(Protocol.S_CHUHAN_SYNC_CONFIG % 20000, builder);
        }
    }

    /**
     * 被任命了减益buff的玩家银两产出会减少
     */
    public int getPositionReduce() {
        ChuHanConfig config = ChuHanMgr.getConfig();
        if (config == null) {
            return 0;
        }
        if (!ActivityMgr.activityInRewardPeriod(config.getActivityInfo())) {
            return 0;
        }
        if (userData == null || userData.getPositionId() == eTongBingPosition.None.getValue()) {
            return 0;
        }
        Map<Integer, ChuHanTitleConfig> tongBingTitleConfigMap = config.getTitleConfigMap();
        if (!tongBingTitleConfigMap.containsKey(userData.getPositionId())) {
            return 0;
        }
        ChuHanTitleConfig tongBingTitleConfig = tongBingTitleConfigMap.get(userData.getPositionId());
        if (tongBingTitleConfig.getType() != 2) {
            return 0;
        }
        // 增益buff
        if (1000 - tongBingTitleConfig.getEffect() <= 0) {
            return 0;
        }
        return -tongBingTitleConfig.getEffect();
    }

    /**
     * 城主任命在线玩家
     */
    public void winnerAppoint(int position) {
        if (userData.getPositionId() == eTongBingPosition.None.getValue() || userData.getPositionId() != position) {
            userData.setPositionId(position);
        }
        player.getModule(EarnSpeedModule.class).scheduleAddSilver();
        syncUserData();
    }

    /**
     * 是否为城主
     */
    public boolean isChuHanMaster() {
        return userData != null && userData.getPositionId() == eTongBingPosition.Master.getValue();
    }

    /**
     * 膜拜
     */
    public void worship() {
        ChuHanProto.ChuHanCityWinnerWorshipRespMsg.Builder respMsg = ChuHanProto.ChuHanCityWinnerWorshipRespMsg.newBuilder();
        respMsg.setRet(0);
        ChuHanConfig config = ChuHanMgr.getConfig();
        if (config == null || !ActivityMgr.activityInRewardPeriod(config.getActivityInfo())) {
            respMsg.setRet(GameErrorCode.E_CHUHAN_NO_OPERATE_TIME);
            player.sendPacket(Protocol.S_CHUHAN_CITY_WINNER_WORSHIP % 20000, respMsg);
            return;
        }
        long zeroTime = DateHelper.getTodayZeroTimeStamp();
        if (userData.getWorshipTime() >= zeroTime) {
            respMsg.setRet(GameErrorCode.E_CHUHAN_WORSHIP_DO);
            player.sendPacket(Protocol.S_CHUHAN_CITY_WINNER_WORSHIP % 20000, respMsg);
            return;
        }
        userData.setWorshipTime(System.currentTimeMillis());
        String reward = ChuHanMgr.getWorshipReward();
        player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.ChuHan, eLogMoneyType.ChuHanWorshipReward);

        respMsg.setReward(reward);
        respMsg.setWorshipTime(userData.getWorshipTime());
        player.sendPacket(Protocol.S_CHUHAN_CITY_WINNER_WORSHIP % 20000, respMsg);
        syncUserData();
    }

    /**
     * 能否购买统兵演武礼包
     */
    public boolean canBuyRechargeGift(int mallId) {
        ChuHanConfig config = ChuHanMgr.getConfig();
        if (config == null) {
            return false;
        }
        if (!ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return false;
        }

        long stage1BeginTime = config.getStage1TimeList().get(0).get(0);
        long zeroTimeStamp = DateHelper.getZeroTimeStamp(stage1BeginTime);
        long now = System.currentTimeMillis();
        if (now < zeroTimeStamp) {
            return false;
        }
        if (!hasCamp()) {
            return false;
        }

        return true;
    }

    /**
     * 是否有阵营
     */
    public boolean hasCamp() {
        return userData.getCampId() != 0;
    }

    /**
     * 跨服加阵营红包
     */
    public void addCrossRedPacket(GoodsInfo goodsInfo, long num) {
        ChuHanConfig config = ChuHanMgr.getConfig();
        if (config == null || !ActivityMgr.activityInTime(config.getActivityInfo())) {
            log.error("tong bing activity no in time , userId {} , use red packet num {}.", player.getUserId(), num);
            return;
        }

        ChuHanProto.CrossChuHanRedPacketAddReqMsg.Builder builder = ChuHanProto.CrossChuHanRedPacketAddReqMsg.newBuilder();
        builder.setActivityId(config.getActivityInfo().getActivityId());
        builder.setNum((int) num);
        builder.setGoodId(goodsInfo.getGoodsId());
        player.sendUnionActivityGroupPacket(CrossProtocol.C2_CHUHAN_RED_PACKET_ADD, builder, config.getActivityInfo().getActivityId());
    }

    /**
     * 登录时上传数据到跨服
     */
    public void crossLogin() {
        ChuHanConfig config = ChuHanMgr.getConfig();
        if (config != null && ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            int activityId = config.getActivityInfo().getActivityId();

            if (checkNoGroupSyncBaseDataMsg(config)) {
                return;
            }

            ChuHanProto.CrossChuHanLoginReqMsg.Builder builder = ChuHanProto.CrossChuHanLoginReqMsg.newBuilder();
            builder.setActivityId(activityId);
            builder.setUserId(player.getUserId());
            builder.setServerId(GameServer.getInstance().getServerId());
            builder.setUnionUid(player.getUserInfo().getUnionUid());
            builder.addAllPatronsList(ChuHanPb.parseChuHanPatronsListMsg(player.getModule(PatronsModule.class).getUserPatronsList()));
            builder.setUserBaseInfo(PlayerPb.parsePlayerBaseTempMsg(player.getUserInfo()));
            builder.addAllSoldierAddition(player.getModule(PatronsModule.class).getChuHanSoldierAddition());
            player.sendUnionActivityGroupPacket(CrossProtocol.C2_CHUHAN_LOGIN, builder, activityId);
        }
    }

    /**
     * @return false需要再上跨服取数据
     */
    private boolean checkNoGroupSyncBaseDataMsg(ChuHanConfig config) {
        ActivityInfo activityInfo = config.getActivityInfo();

        // 旧版活动，上跨服取
        if (!UnionActivityGroupHelper.needGroup(activityInfo)) {
            return false;
        }

        // 新版活动，还没锁名单，给个假数据
        boolean hadGroup = GameUnionActivityGroupMgr.getGroupMap(config.getActivityInfo().getActivityId()) != null;
        if (!hadGroup) {
            ChuHanProto.ChuHanSyncBaseDataRespMsg.Builder builder = ChuHanProto.ChuHanSyncBaseDataRespMsg.newBuilder();
            builder.setJoinStatus(0); // 未报名
            // builder.setCampId(0);
            builder.setSyncPatronsTime(0);
            builder.setGuide(0);
            builder.setSyncNeedHelpTime(0);
            player.sendPacket(Protocol.S_CHUHAN_SYNC_BASE_DATA % 20000, builder);
            return true;
        }

        // 新版活动，锁完名单有资格，上跨服取
        int groupId = GameUnionActivityGroupMgr.getGroupId(activityInfo.getActivityId(), player.getUserId());
        if (groupId != UnionActivityGroupHelper.NO_GROUP_ID) {
            return false; // 有资格可以走远逻辑
        }

        // 新版活动，锁完名单没资格，给个假数据
        ChuHanProto.ChuHanSyncBaseDataRespMsg.Builder builder = ChuHanProto.ChuHanSyncBaseDataRespMsg.newBuilder();
        builder.setJoinStatus(3); // 3商会未入选
        // builder.setCampId(0);
        builder.setSyncPatronsTime(0);
        builder.setGuide(0);
        builder.setSyncNeedHelpTime(0);
        player.sendPacket(Protocol.S_CHUHAN_SYNC_BASE_DATA % 20000, builder);
        return true;
    }

    /**
     * 初始化玩家数据
     */
    private synchronized void initUserData() {
        ChuHanConfig config = ChuHanMgr.getConfig();
        if (config != null && ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            if (userData == null || config.getActivityInfo().getActivityId() != userData.getActivityId()) {
                ChuHanUserData tempUserData = new ChuHanUserData();
                tempUserData.setActivityId(config.getActivityInfo().getActivityId());
                tempUserData.setUserId(getUserId());
                tempUserData.setWorshipTime(0);
                tempUserData.setPositionId(0);
                tempUserData.setZhanGong(0);
                tempUserData.setSkinExchangeMap(new ConcurrentHashMap<>());
                tempUserData.setInsertOption();
                userData = tempUserData;
            }
        }
    }

    // 同步玩家数据
    public void syncUserData() {
        ChuHanConfig config = ChuHanMgr.getConfig();
        if (config != null && ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            ChuHanProto.ChuHanUserDataSyncMsg.Builder respMsg = ChuHanProto.ChuHanUserDataSyncMsg.newBuilder();
            respMsg.setActivityId(userData.getActivityId());
            respMsg.setWorshipTime(userData.getWorshipTime());
            respMsg.setPositionId(userData.getPositionId());
            respMsg.setCampId(userData.getCampId());
            respMsg.setZhanGong(userData.getZhanGong());
            respMsg.setWinnerId(0L);
            for (Map.Entry<Integer, Integer> entry : userData.getSkinExchangeMap().entrySet()) {
                ChuHanProto.ChuHanSkinExchangeTemp.Builder temp = ChuHanProto.ChuHanSkinExchangeTemp.newBuilder();
                temp.setSkinId(entry.getKey());
                temp.setCount(entry.getValue());
                respMsg.addSkinExchange(temp);
            }

            boolean hadGroup = GameUnionActivityGroupMgr.getGroupMap(config.getActivityInfo().getActivityId()) != null;
            int groupId = GameUnionActivityGroupMgr.getGroupId(config.getActivityInfo().getActivityId(), getUserId());
            if (!hadGroup || groupId == UnionActivityGroupHelper.NO_GROUP_ID) {
                // 没资格不发跨服
                respMsg.setWinnerId(0);
                player.sendPacket(Protocol.S_CHUHAN_USER_DATA_SYNC % 20000, respMsg);
            } else {
                // 有资格才上跨服
                player.sendUnionActivityGroupPacket(CrossProtocol.C2_CHUHAN_SYNC_USER_DATA, respMsg, config.getActivityInfo().getActivityId());
            }
        }
    }

    /**
     * 加阵营红包成就进度
     */
    public void notifyRedPackValue(int activityId, long value) {
        if (userData.getActivityId() == activityId) {
            player.notifyListenerAndSync(eGamePlayerEventType.ChuHanCampBoxScore.getValue(), new TongBingRedPacketValueArgs(activityId, value));
        }
    }

    /**
     * 更新用户数据
     */
    public void updateUserData(ChuHanProto.CrossChuHanSyncUserDataMsg reqMsg) {
        ChuHanConfig config = ChuHanMgr.getConfig();
        if (config == null) {
            return;
        }
        if (!ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return;
        }
        if (userData == null) {
            return;
        }
        // 其他需要同步到游戏服的数据在这处理
        userData.setCampId(reqMsg.getCampId());
        userData.setZhanGong(reqMsg.getZhanGong());
        // 同步玩家数据
        syncUserData();
    }
}
